package com.kerrykidz.scmstock.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.PrimaryKeyGenerator;
import com.kerrykidz.common.PrimaryKeyGenerator.BusinessType;
import com.kerrykidz.common.service.ICommonService;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmInStgEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmInstgPrdEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmPrdStgEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmPurOrderEntity;
import com.kerrykidz.scminvoicing.service.IScmInvocingProductInfoService;
import com.kerrykidz.scmstock.service.IStockGoodsInService;
import com.kerrykidz.system.dao.model.GblSecBranEntity;
import com.kerrykidz.system.dao.model.SysParaEntity;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;

/**
 * 
 * @ClassName: StockGoodsInController
 * @description: 商品入库控制器
 * @author: huanjiang
 * @date: 2014年8月8日 上午11:23:23
 * @version: V1.0
 * 
 */
@RequestMapping("StockGoodsIn")
@Controller
public class StockGoodsInController {

	@Autowired
	private IStockGoodsInService iStockGoodsInService;

	@Autowired
	private IScmInvocingProductInfoService iScmInvocingProductInfoService;

	@Autowired
	private ICommonService commonService;

	/**
	 * @Title: findScmInStgById
	 * @Description: 查询入库单分页
	 * @param pagebean
	 * @date: 2014年8月8日
	 * @return: ScmInStgEntity
	 */
	@RequestMapping(value = "findScmInStg", method = RequestMethod.POST)
	@ResponseBody
	public ScmInStgEntity findScmInStg(ScmInStgEntity pagebean)
			throws RDPException {
		return this.iStockGoodsInService.findScmInStg(pagebean);
	}

	/**
	 * @Title: findScmPurOrderForStock
	 * @Description:获得新增入库需要的采购订单实例 </br>附加条件为订单编号、下单时间、到货状态
	 * @param: <@param scmPurOrder
	 * @date: 2014年8月12日
	 * @return: List<ScmPurOrderEntity>
	 * @throws ParseException
	 */
	@RequestMapping(value = "findScmPurOrderForStock", method = RequestMethod.POST)
	@ResponseBody
	public ScmPurOrderEntity findScmPurOrderForStock(
			@RequestParam(value = "startSearchTime", required = false) String startSearchTime,
			@RequestParam(value = "endSearchTime", required = false) String endSearchTime,
			ScmPurOrderEntity pagebean) throws RDPException, ParseException {
		Date startDate = null;
		Date endDate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		if (startSearchTime == null || startSearchTime.length() == 0) {
			startDate = new Date(0);
		} else {
			startDate = sdf.parse(startSearchTime + " 00:00:00");
		}
		if (endSearchTime != null && endSearchTime.length() != 0) {
			endDate = sdf.parse(endSearchTime + " 23:59:59");
		}
		pagebean.setStartTime(startDate);
		pagebean.setEndTime(endDate);
		return this.iStockGoodsInService.findScmPurOrderForStock(pagebean);
	}

	/**
	 * @Title: toStockAddGoodsIn
	 * @Description: 跳转到新增入库页面
	 * @param: session 登录用户的信息
	 * @date: 2014年 8月8日
	 * @return: String
	 */
	@RequestMapping("toStockAddGoodsIn")
	public ModelAndView toStockAddGoodsIn() {
		ModelAndView mav = new ModelAndView("stock/stock_addGoodsIn");
		UserInfo userInfo = UserUtil.getUserFromSession();
		if (userInfo != null) {
			String userName = userInfo.getName();
			String storeName = userInfo.getBranName();// 门店名
			String storeId = userInfo.getBranId();
			String todayTime = new SimpleDateFormat("yyyy-MM-dd")
					.format(new Date());
			String stockId = PrimaryKeyGenerator.getPrimaryKey(BusinessType.RK,
					userInfo.getAbbrCode());
			HashMap<String, String> infoMap = new HashMap<String, String>();
			infoMap.put("userName", userName);
			infoMap.put("storeName", storeName);
			infoMap.put("todayTime", todayTime);
			infoMap.put("stockId", stockId);
			infoMap.put("storeId", storeId);
			mav.addObject("map", infoMap);
		}
		return mav;
	}

	/**
	 * 
	 * @Title: findGblScmPrdEntity
	 * @Description:分页显示新增入库时订单包含的商品
	 * @param: @param fkPurordId 入库订单id
	 * @param: @param pagebean
	 * @date: 2014年8月12日
	 * @return: GblScmPrdEntity
	 * @throws RDPException
	 * 
	 */
	@RequestMapping(value = "findGblScmPrdEntity", method = RequestMethod.POST)
	@ResponseBody
	public List<GblScmPrdEntity> findGblScmPrdEntity(
			@RequestParam("fkPurordId") String fkPurordId,
			GblScmPrdEntity pagebean) throws RDPException {
		List<GblScmPrdEntity> beanList = iScmInvocingProductInfoService
				.getProductListForCollection(fkPurordId);
		return beanList;
	}

	/**
	 * @Title: findGblScmPrdEntity
	 * @Description: 入库清单
	 * @param fkPurordId
	 *            入库单号
	 * @param pagebean
	 *            商品实体对象
	 * @param scmInstgPrd
	 * @date: 2014年8月21日
	 * @return: GblScmPrdEntity
	 * @throws RDPException
	 */
	@RequestMapping(value = "findGblScmPrdEntityForDetail", method = RequestMethod.POST)
	@ResponseBody
	public List<GblScmPrdEntity> findGblScmPrdEntityForDetail(
			@RequestParam("fkPurordId") String fkPurordId,
			ScmInstgPrdEntity scmInstgPrd) throws RDPException {
		List<ScmInstgPrdEntity> list = iStockGoodsInService
				.findScmInstgPrd(scmInstgPrd.getFkInstgId());
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (list.size() > 0) {
			for (ScmInstgPrdEntity scmInstg : list) {
				map.put(scmInstg.getFkPrdId(), scmInstg);
			}
		}
		List<GblScmPrdEntity> beanList = iScmInvocingProductInfoService
				.getProductListForCollection(fkPurordId);

		if (beanList.size() > 0) {

			for (GblScmPrdEntity gblScmPrd : beanList) {
				ScmInstgPrdEntity commAndInstgCnt = (ScmInstgPrdEntity) map
						.get(gblScmPrd.getPkPrdId());
				if (commAndInstgCnt != null) {
					gblScmPrd.setPrdInstgCnt(commAndInstgCnt.getInstgCnt());
					gblScmPrd.setComments(commAndInstgCnt.getComments());
				}
			}
		}
		return beanList;

	}

	/**
	 * 
	 * @Title: stockGoodsInOpertion
	 * @Description: 商品入库后插入或更新数据
	 * @param session
	 *            包含登录用户信息
	 * @param stockId
	 *            入库编号
	 * @param content
	 *            表格数据
	 * @param purordId
	 *            采购编号
	 * @param isGoOn
	 *            true 入库继续 false 入库
	 * @return
	 * @throws RDPException
	 * @date: 2014年8月14日
	 * @return: String
	 * @throws
	 */
	@RequestMapping("stockGoodsInOpertion")
	public ModelAndView stockGoodsInOpertion(
			@RequestParam("stockId") String stockId,
			@RequestParam("content") String content,
			@RequestParam("purordId") String purordId,
			@RequestParam(value = "isGoOn", required = false) String isGoOn,
			@RequestParam("attFile") String attFile) throws RDPException {
		UserInfo userInfo = UserUtil.getUserFromSession();
		iStockGoodsInService.stockGoodsInOpertion(userInfo, stockId, content,
				purordId, attFile);
		ModelAndView mav = new ModelAndView("stock/stock_goodsIn");
		if ("true".equals(isGoOn)) {
			mav = toStockAddGoodsIn();// 入库并继续
		}
		return mav;
	}

	/**
	 * @throws UnsupportedEncodingException
	 * @Title: uploadStockFile
	 * @Description: 上传入库单附件
	 * @param: @param file
	 * @date: 2014年8月15日
	 * @return: String
	 * @throws
	 */
	@RequestMapping(value = "/uploadFile")
	@ResponseBody
	public String uploadStockFile(
			@RequestParam(value = "file", required = false) MultipartFile file)
			throws UnsupportedEncodingException {
		UserInfo userInfo = UserUtil.getUserFromSession();
		if (null == userInfo) {
			return null;
		}
		SysParaEntity para = commonService
				.findSysParaById(Constants.SYS_BASE_PATH_STOCK);
		String fileName = userInfo.getAbbrCode() + file.getOriginalFilename();
		File targetFile = new File(para.getParaValue(), fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		fileName = URLEncoder.encode(fileName, "UTF-8");
		return fileName;
	}

	/**
	 * 
	 * @Title: rollBackForStockIn
	 * @Description: 删除入库单
	 * @param: session 包含登录用户信息
	 * @param: fkInstgId 入库单号
	 * @date: 2014年8月21日
	 * @return: String
	 * @throws RDPException
	 * 
	 */
	@RequestMapping("rollBackForStockIn")
	@ResponseBody
	public String rollBackForStockIn(String fkInstgId) throws RDPException {
		ScmPrdStgEntity scmPrdStg = new ScmPrdStgEntity();
		UserInfo userInfo = UserUtil.getUserFromSession();
		scmPrdStg.setModiBy(userInfo.getName());
		boolean success = iStockGoodsInService.rollBackForStockIn(fkInstgId,
				scmPrdStg);
		if (success) {
			return Constants.SUCCESS;
		}
		return Constants.FAILURE;
	}

	/**
	 * @Title: toStock_goodsIn
	 * @Description: 跳转到商品入库
	 * @date: 2014年8月8日
	 * @return: String
	 * @throws RDPException
	 */
	@RequestMapping("toStock_goodsIn")
	public ModelAndView toStock_goodsIn() throws RDPException {
		ModelAndView mav = new ModelAndView("stock/stock_goodsIn");
		UserInfo userInfo = UserUtil.getUserFromSession();
		if (userInfo != null) {
			String brandId = userInfo.getBranId();
			List<GblSecBranEntity> branList = null;
			if (brandId.toUpperCase().indexOf("ZB") != -1)// 总部
			{
				branList = commonService.getBranListForStock(null);
				mav.addObject("branList", branList);
				for (GblSecBranEntity gblSecBranEntity : branList) {
					brandId = gblSecBranEntity.getPkBranId();
					if (brandId.toUpperCase().indexOf("WX") != -1) {
						mav.addObject("branId", brandId);
					}
				}
			} else {
				branList = commonService.getBranListForStock(brandId);
				mav.addObject("branId", brandId);
				mav.addObject("branList", branList);
			}
		}
		return mav;
	}

	/**
	 * @Title: toStock_addGoodsIn
	 * @Description: 跳转到新增入库
	 * @date: 2014年8月19日
	 * @return: String
	 * @throws RDPException
	 */
	@RequestMapping("toStock_addGoodsIn")
	public ModelAndView toStock_addGoodsIn() throws RDPException {
		ModelAndView mav = new ModelAndView("stock/stock_addGoodsIn");
		return mav;
	}

	/**
	 * @Title: toStock_goodsInDetail
	 * @Description: 跳转入库清单页面
	 * @date: 2014年8月8日
	 * @return: String
	 */
	@RequestMapping("/toStock_goodsInDetail")
	public String toStock_goodsInDetail() {
		return "stock/stock_goodsInDetail";
	}

	/**
	 * 
	 * @Title: selectScmInStg
	 * @Description: 入库清单
	 * @param: pkInstgId
	 * @date: 2014年8月21日
	 * @return: ModelAndView
	 * @throws RDPException
	 * @throws UnsupportedEncodingException
	 * 
	 */
	@RequestMapping("/selectScmInstg")
	public ModelAndView selectScmInStg(String pkInstgId) throws RDPException,
			UnsupportedEncodingException {
		ScmInStgEntity inStgEntity = iStockGoodsInService
				.selectScmInStg(pkInstgId);
		String Time = new SimpleDateFormat("yyyy-MM-dd").format(inStgEntity
				.getModiTime());
		ModelAndView mv = new ModelAndView("stock/stock_goodsInDetail");
		mv.addObject("inStgEntity", inStgEntity);
		mv.addObject("key", Constants.SYS_BASE_PATH_STOCK);
		mv.addObject("Time", Time);
		mv.addObject("pkInstgId", pkInstgId);
		return mv;
	}

}
